package com.twfpro.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5工具
 * 
 * @author 高文
 *
 */
public class MD5Util
{
	public static String encrypt(File file) throws FileNotFoundException, IOException, NoSuchAlgorithmException
	{
		try (FileInputStream in = new FileInputStream(file))
		{
			MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(byteBuffer);
			String md5 = new BigInteger(1, md.digest()).toString(16);
			if (md5.length() < 32)
			{
				md5 = String.format("%" + (32 - md5.length()) + "d%s", 0, md5);
			}
			return md5;
		}
	}

	public static String encrypt(String str)
	{
		try
		{
			MessageDigest md;
			md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes("UTF-8"));
			String md5 = new BigInteger(1, md.digest()).toString(16);
			while (md5.length() < 32)
			{
				md5 = "0" + md5;
			}
			return md5;
		}
		catch (NoSuchAlgorithmException | UnsupportedEncodingException e)
		{
			e.printStackTrace();
			return null;
		}
	}
}